#ifndef PDXPMODEL_H
#define PDXPMODEL_H

#include "protocol.h"

#include <QFile>
#include <QVector>
#include <QDataStream>
#include "dataview.h"

struct PDXP {
    quint8 VER;
    quint16 MID;
    quint32 SID;
    quint32 DID;
    quint32 BID;
    quint32 NO;
    quint8 FLAG;
    quint32 Res;
    quint16 JD;
    quint32 JS;
    quint16 LEN;

    QDate date(void);
    QTime time(void);
};

QDataStream& operator >>(QDataStream& is, PDXP& pdxp);

class PDXPModel : public ProtocolTableModel
{
    Q_OBJECT
public:
    PDXPModel(const QString& fileName, QObject *parent = 0);

signals:
    void openTempFile(const QString fileName);

public slots:

private:
    mutable QFile file;
    int showColumns;
    QVector<qint64> records;
    qint64 firstPos;
    qint64 searchPos;
    qint64 showCount;
    mutable int cacheRow;
    mutable PDXP pdxp;
    mutable QByteArray record;

    void loadRecord(int row) const;
    bool calcRecords(void);
    int maxDisplaySize(void) const;
    void filterSize(const QModelIndex& index);
    void filterMID(const QModelIndex& index);
    void filterSID(const QModelIndex& index);
    void filterDID(const QModelIndex& index);
    void filterBID(const QModelIndex& index);
    void filterJDJS(const QModelIndex& index);
    void filterLEN(const QModelIndex& index);
    qint64 searchFirst(void);

    // QAbstractItemModel interface
public:
    int rowCount(const QModelIndex &parent) const;
    int columnCount(const QModelIndex &parent) const;
    QVariant data(const QModelIndex &index, int role) const;
    void fetchMore(const QModelIndex &parent);
    bool canFetchMore(const QModelIndex &parent) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

    // ProtocolTableModel interface
public:
    qint64 position(const QModelIndex &index);
    QModelIndex locate(qint64 pos);
    bool deleteRows(const QString &fileName, const QModelIndexList &rows);
    bool deleteColumns(const QString &fileName, const QModelIndexList &cols);
    bool saveRows(const QString &fileName, const QModelIndexList &rows);
    bool saveColumns(const QString &fileName, const QModelIndexList &cols);
    bool supportFilter(const QModelIndex& index);
    void filter(const QModelIndex& index);
};

#endif // PDXPMODEL_H
